<template>
  <view class="honor-info-form">
    <!-- 使用通用展示组件 -->
    <DetailDisplayList
      :config="config"
      :list="honorList"
      :loading="loading"
      @add="handleAddHonor"
      @delete="handleDeleteHonor"
    >
      <!-- 自定义文件展示 -->
      <template #file-display="{ item }">
        <view v-if="item.TitleDocument" class="file-attachment">
          <button class="file-button" @click="previewFile(item.TitleDocument)">
            <i
              class="iconfont icon-wenjian"
              style="font-size: 14px; color: #3b82f6; margin-right: 4px"
            ></i>
            {{ item.TitleDocument.FileName || "查看证书" }}
          </button>
        </view>
      </template>
    </DetailDisplayList>

    <!-- 新增弹窗 -->
    <XenUnifiedAddPopup
      v-model:show="showAddPopup"
      :config="honorPopupConfig"
      :person-id="personId"
      :on-submit="handleHonorSubmit"
      @confirm="handleConfirmAdd"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import useActivityApi from "../../api/index";
import type {
  ISysPersonProfessionalTitleView,
  GetRequest,
  IFileAttachment,
  ISysPersonProfessionalTitleVm,
} from "../../api/interface";
import XenUnifiedAddPopup from "./XenUnifiedAddPopup.vue";
import DetailDisplayList from "./DetailDisplayList.vue";
import { honorConfig } from "./popupConfigs";
import { honorDisplayConfig } from "./detailDisplayConfig";

const api = useActivityApi();

// Props
interface Props {
  personId: string;
}

const props = defineProps<Props>();

// 状态管理
const loading = ref(false);
const honorList = ref<ISysPersonProfessionalTitleView[]>([]);
const showAddPopup = ref(false);
const editingHonor = ref<ISysPersonProfessionalTitleView | null>(null);

// 弹框配置
const honorPopupConfig = ref(JSON.parse(JSON.stringify(honorConfig)));

// 详情展示配置
const config = ref(honorDisplayConfig);

// 处理荣誉职称提交
const handleHonorSubmit = async (formData: any) => {
  const submitData: ISysPersonProfessionalTitleVm = {
    Entity: {
      PersonId: props.personId as any,
      TitleName: formData.QualificationName || null, // 使用新的资质名称字段
      TitleLevel: null, // 移除职称级别字段
      CertificateCode: formData.CertificateCode || null,
      SalaryReward: formData.SalaryReward || null,
      TitleDocumentId: null, // 保留原字段但设为null
      CertificateDocumentId: formData.CertificateDocumentId || null, // 使用新的证书文件ID字段
      // 新增字段
      ProfessionalTitleTypeId: formData.ProfessionalTitleTypeId || null,
      QualificationLevel: formData.QualificationLevel || null,
      IssuingAuthority: formData.IssuingAuthority || null,
      ObtainedDate: formData.ObtainedDate
        ? new Date(formData.ObtainedDate)
        : null,
      ExpiryDate: formData.ExpiryDate ? new Date(formData.ExpiryDate) : null,
      Remark: formData.Remark || null,
      QualificationName: formData.QualificationName || null, // 添加资质名称字段
      ProfessionalTitleTypeName: null, // 添加资质类别名称字段，提交时为null，由后端填充
    },
    ActionName: null,
    IsMyApprove: false,
  };

  await api.addHonorTitle(submitData);
};

// 加载荣誉职称列表
const loadHonorList = async () => {
  if (!props.personId) return;

  loading.value = true;
  try {
    const params: GetRequest = {
      Limit: 50,
      Page: 1,
      PersonId: props.personId,
      SortInfo: null,
    };

    const res = await api.getHonorTitle(params);
    if (res && res.Data) {
      honorList.value = res.Data;
    }
  } catch (error) {
    console.error("加载荣誉职称失败:", error);
    uni.showToast({
      title: "加载荣誉职称失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 加载资质类别数据
const loadProfessionalTitleTypes = async () => {
  try {
    const res = await api.GetSysPersonProfessionalTitleTypes();
    console.log("资质类别API返回数据:", res);

    if (res && Array.isArray(res)) {
      // 找到资质类别字段并更新选项
      const section = honorPopupConfig.value.sections.find(
        (s: any) => s.key === "honor_info",
      );
      if (section) {
        const row = section.rows.find((r: any) => r.key === "row1");
        if (row) {
          const field = row.fields.find(
            (f: any) => f.key === "ProfessionalTitleTypeId",
          );
          if (field) {
            const options = res.map((item) => {
              console.log("处理资质类别项:", item);
              return {
                value: item.Value,
                text: item.Text,
              };
            });
            console.log("转换后的选项数据:", options);
            field.options = options;
          }
        }
      }
    } else {
      console.log("资质类别数据为空或格式不正确:", res);
    }
  } catch (error) {
    console.error("加载资质类别失败:", error);
    uni.showToast({
      title: "加载资质类别失败",
      icon: "none",
    });
  }
};

// 新增荣誉职称
const handleAddHonor = async () => {
  editingHonor.value = null;
  // 加载资质类别数据
  await loadProfessionalTitleTypes();
  showAddPopup.value = true;
};

// 删除荣誉职称
const handleDeleteHonor = (item: any) => {
  const id = item.ID;
  if (!id) return;

  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条荣誉职称记录吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          await api.deleteHonorTitle([id]);
          // 重新加载列表
          await loadHonorList();
          uni.showToast({
            title: "删除成功",
            icon: "success",
          });
        } catch (error) {
          console.error("删除荣誉职称失败:", error);
          uni.showToast({
            title: "删除失败",
            icon: "error",
          });
        }
      }
    },
  });
};

// 预览文件
const previewFile = async (file: IFileAttachment) => {
  if (!file?.ID) return;

  try {
    await api.previewFile(file.ID, file.FileName || undefined);
  } catch (error) {
    console.error("预览文件失败:", error);
    uni.showToast({
      title: "预览失败",
      icon: "none",
    });
  }
};

// 确认新增
const handleConfirmAdd = () => {
  showAddPopup.value = false;
  editingHonor.value = null;
  loadHonorList();
};

// 监听personId变化
watch(() => props.personId, loadHonorList, { immediate: true });

// 页面加载
onMounted(() => {
  if (props.personId) {
    loadHonorList();
  }
});
</script>

<style lang="scss" scoped>
.honor-info-form {
  // 保留文件按钮样式，因为在自定义插槽中使用
  .file-attachment {
    .file-button {
      background: rgba(59, 130, 246, 0.1);
      color: #3b82f6;
      border: 1rpx solid #3b82f6;
      border-radius: 8rpx;
      padding: 8rpx 16rpx;
      font-size: 24rpx;
      display: flex;
      align-items: center;
      transition: all 0.3s ease;

      &:active {
        background: rgba(59, 130, 246, 0.2);
      }
    }
  }
}
</style>
